package com.hmily.dubbo.consumer.async;

import com.hmily.dubbo.api.async.AsyncUserQueryFacade;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.Supplier;

/**
 * <h1>利用 java 代码来启动消费方。</h1>
 *
 * @author hmilyylimh
 * ^_^
 * @version 0.0.1
 * ^_^
 * @date 2021-10-18
 */
public class AsyncCompletableFutureConsumerApplication {

    public static void main(String[] args) throws IOException {
        // 设置应用服务名称
        ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-consumer");
        // 设置注册中心的地址
        RegistryConfig registryConfig = new RegistryConfig("zookeeper://127.0.0.1:2181");

        // 创建引用 AsyncUserQueryFacade 这个服务的对象
        ReferenceConfig<AsyncUserQueryFacade> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setApplication(applicationConfig);
        referenceConfig.setRegistry(registryConfig);
        referenceConfig.setInterface(AsyncUserQueryFacade.class);
        referenceConfig.setTimeout(12000);

        // 直接拿到引用的代理对象，然后进行远程调用
        AsyncUserQueryFacade asyncUserQueryFacade = referenceConfig.get();
        CompletableFuture<String> completableFuture = asyncUserQueryFacade.queryUserByName("yuki");
        completableFuture.whenComplete((value, e) -> {
            if(e != null){
                e.printStackTrace();
            } else {
                System.out.println("whenComplete 等回来的结果为: " + value);
            }
        });

        // 阻塞等待
        System.out.println("阻塞等待~~~");
        System.in.read();
    }

    public static void main1(String[] args) throws Throwable {
        // 设置应用服务名称
        ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-consumer");
        // 设置注册中心的地址
        RegistryConfig registryConfig = new RegistryConfig("zookeeper://127.0.0.1:2181");

        // 创建引用 AsyncUserQueryFacade 这个服务的对象
        ReferenceConfig<AsyncUserQueryFacade> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setApplication(applicationConfig);
        referenceConfig.setRegistry(registryConfig);
        referenceConfig.setInterface(AsyncUserQueryFacade.class);
        referenceConfig.setTimeout(12000);

        // 直接拿到引用的代理对象，然后进行远程调用
        AsyncUserQueryFacade asyncUserQueryFacade = referenceConfig.get();
        CompletableFuture<String> completableFuture =
                CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                return asyncUserQueryFacade.queryUserById("G314");
            }
        });
        System.out.println(completableFuture.get());

        // 阻塞等待
        System.in.read();
    }
}
